from fastapi import APIRouter, Depends, HTTPException, Body, Path, Query
from pydantic import BaseModel
from typing import List, Optional
import database
from auth import get_current_user
import logging
from datetime import datetime

# 配置日志
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)

router = APIRouter(tags=["notifications"])

# 通知模型
class NotificationBase(BaseModel):
    title: str
    content: str
    type: str

class NotificationCreate(NotificationBase):
    pass

class NotificationUpdate(NotificationBase):
    pass

class Notification(NotificationBase):
    id: int
    created_by: int
    created_at: datetime
    updated_at: Optional[datetime] = None
    is_active: bool = True

# 获取所有系统通知
@router.get("/system", response_model=List[Notification])
async def get_system_notifications(current_user: int = Depends(get_current_user)):
    """获取所有系统通知"""
    try:
        # 查询系统通知
        query = """
        SELECT 
            n.id, n.title, n.content, n.type, n.created_by, 
            n.created_at, n.updated_at, n.is_active
        FROM 
            system_notifications n
        WHERE 
            n.is_active = 1
        ORDER BY 
            n.created_at DESC
        """
        
        notifications = await database.fetch_all(query)
        return notifications
    except Exception as e:
        logger.error(f"获取系统通知失败: {str(e)}")
        raise HTTPException(status_code=500, detail=f"获取系统通知失败: {str(e)}")

# 创建系统通知（仅管理员）
@router.post("/system/create", response_model=Notification)
async def create_system_notification(
    notification: NotificationCreate = Body(...),
    current_user: int = Depends(get_current_user)
):
    """创建新的系统通知（需要管理员权限）"""
    try:
        # 记录用户信息
        logger.info(f"当前用户信息: {current_user}")
        
        # 提取用户ID - 处理current_user可能是对象的情况
        user_id = current_user
        if hasattr(current_user, 'id'):
            user_id = current_user.id
        elif isinstance(current_user, dict) and 'id' in current_user:
            user_id = current_user['id']
        
        logger.info(f"提取的用户ID: {user_id}")
        
        # 检查用户是否为管理员
        user_query = """
        SELECT is_admin FROM users WHERE id = %s
        """
        user = await database.fetch_one(user_query, (user_id,))
        
        # 记录详细的调试信息
        logger.info(f"用户ID: {user_id}, 用户数据: {user}")
        
        if not user:
            logger.error(f"用户ID {user_id} 不存在")
            raise HTTPException(status_code=403, detail="权限不足，用户不存在")
        
        # 获取is_admin值并记录类型信息
        is_admin = user["is_admin"]
        logger.info(f"is_admin值: {is_admin}, 类型: {type(is_admin)}")
        
        # 更健壮的管理员检查：处理不同的数据类型
        admin_status = False
        if isinstance(is_admin, bool):
            admin_status = is_admin
        elif isinstance(is_admin, int):
            admin_status = is_admin == 1
        elif isinstance(is_admin, str):
            admin_status = is_admin.lower() in ('1', 'true', 'yes')
        
        logger.info(f"管理员状态判断结果: {admin_status}")
            
        if not admin_status:
            logger.error(f"用户ID {user_id} 没有管理员权限，is_admin值: {is_admin}")
            raise HTTPException(status_code=403, detail="权限不足，仅管理员可创建系统通知")
        
        # 插入新通知
        query = """
        INSERT INTO system_notifications (title, content, type, created_by)
        VALUES (%s, %s, %s, %s)
        """
        
        values = (
            notification.title,
            notification.content,
            notification.type,
            user_id
        )
        
        notification_id = await database.execute(query, values)
        logger.info(f"成功创建系统通知，ID: {notification_id}")
        
        # 获取新创建的通知
        new_notification = await database.fetch_one(
            """
            SELECT 
                id, title, content, type, created_by, 
                created_at, updated_at, is_active
            FROM 
                system_notifications
            WHERE 
                id = %s
            """,
            (notification_id,)
        )
        
        return new_notification
    except HTTPException as e:
        raise e
    except Exception as e:
        logger.error(f"创建系统通知失败: {str(e)}")
        raise HTTPException(status_code=500, detail=f"创建系统通知失败: {str(e)}")

# 更新系统通知（仅管理员）
@router.put("/system/{notification_id}", response_model=Notification)
async def update_system_notification(
    notification_id: int = Path(...),
    notification: NotificationUpdate = Body(...),
    current_user: int = Depends(get_current_user)
):
    """更新系统通知（需要管理员权限）"""
    try:
        # 提取用户ID - 处理current_user可能是对象的情况
        user_id = current_user
        if hasattr(current_user, 'id'):
            user_id = current_user.id
        elif isinstance(current_user, dict) and 'id' in current_user:
            user_id = current_user['id']
        
        logger.info(f"提取的用户ID: {user_id}")
        
        # 检查用户是否为管理员
        user_query = """
        SELECT is_admin FROM users WHERE id = %s
        """
        user = await database.fetch_one(user_query, (user_id,))
        
        # 记录详细的调试信息
        logger.info(f"用户ID: {user_id}, 用户数据: {user}")
        
        if not user:
            logger.error(f"用户ID {user_id} 不存在")
            raise HTTPException(status_code=403, detail="权限不足，用户不存在")
        
        # 获取is_admin值并记录类型信息
        is_admin = user["is_admin"]
        logger.info(f"is_admin值: {is_admin}, 类型: {type(is_admin)}")
        
        # 更健壮的管理员检查：处理不同的数据类型
        admin_status = False
        if isinstance(is_admin, bool):
            admin_status = is_admin
        elif isinstance(is_admin, int):
            admin_status = is_admin == 1
        elif isinstance(is_admin, str):
            admin_status = is_admin.lower() in ('1', 'true', 'yes')
        
        logger.info(f"管理员状态判断结果: {admin_status}")
            
        if not admin_status:
            logger.error(f"用户ID {user_id} 没有管理员权限，is_admin值: {is_admin}")
            raise HTTPException(status_code=403, detail="权限不足，仅管理员可更新系统通知")
        
        # 更新通知
        query = """
        UPDATE system_notifications
        SET title = %s, content = %s, type = %s, updated_by = %s
        WHERE id = %s
        """
        
        values = (
            notification.title,
            notification.content,
            notification.type,
            user_id,
            notification_id
        )
        
        result = await database.execute(query, values)
        
        # 获取更新后的通知
        updated_notification = await database.fetch_one(
            """
            SELECT 
                id, title, content, type, created_by, 
                created_at, updated_at, is_active
            FROM 
                system_notifications
            WHERE 
                id = %s
            """,
            (notification_id,)
        )
        
        if not updated_notification:
            raise HTTPException(status_code=404, detail="通知不存在或已被删除")
        
        return updated_notification
    except HTTPException as e:
        raise e
    except Exception as e:
        logger.error(f"更新系统通知失败: {str(e)}")
        raise HTTPException(status_code=500, detail=f"更新系统通知失败: {str(e)}")

# 删除系统通知（仅管理员）
@router.delete("/system/{notification_id}")
async def delete_system_notification(
    notification_id: int = Path(...),
    current_user: int = Depends(get_current_user)
):
    """删除系统通知（需要管理员权限）"""
    try:
        # 提取用户ID - 处理current_user可能是对象的情况
        user_id = current_user
        if hasattr(current_user, 'id'):
            user_id = current_user.id
        elif isinstance(current_user, dict) and 'id' in current_user:
            user_id = current_user['id']
        
        logger.info(f"提取的用户ID: {user_id}")
        
        # 检查用户是否为管理员
        user_query = """
        SELECT is_admin FROM users WHERE id = %s
        """
        user = await database.fetch_one(user_query, (user_id,))
        
        # 记录详细的调试信息
        logger.info(f"用户ID: {user_id}, 用户数据: {user}")
        
        if not user:
            logger.error(f"用户ID {user_id} 不存在")
            raise HTTPException(status_code=403, detail="权限不足，用户不存在")
        
        # 获取is_admin值并记录类型信息
        is_admin = user["is_admin"]
        logger.info(f"is_admin值: {is_admin}, 类型: {type(is_admin)}")
        
        # 更健壮的管理员检查：处理不同的数据类型
        admin_status = False
        if isinstance(is_admin, bool):
            admin_status = is_admin
        elif isinstance(is_admin, int):
            admin_status = is_admin == 1
        elif isinstance(is_admin, str):
            admin_status = is_admin.lower() in ('1', 'true', 'yes')
        
        logger.info(f"管理员状态判断结果: {admin_status}")
            
        if not admin_status:
            logger.error(f"用户ID {user_id} 没有管理员权限，is_admin值: {is_admin}")
            raise HTTPException(status_code=403, detail="权限不足，仅管理员可删除系统通知")
        
        # 软删除通知（设置为非活动状态）
        query = """
        UPDATE system_notifications
        SET is_active = 0, updated_by = %s
        WHERE id = %s
        """
        
        values = (user_id, notification_id)
        
        result = await database.execute(query, values)
        
        return {"message": "通知已成功删除"}
    except HTTPException as e:
        raise e
    except Exception as e:
        logger.error(f"删除系统通知失败: {str(e)}")
        raise HTTPException(status_code=500, detail=f"删除系统通知失败: {str(e)}")

# 标记通知为已读
@router.post("/system/read/{notification_id}")
async def mark_notification_as_read(
    notification_id: int = Path(...),
    current_user: int = Depends(get_current_user)
):
    """将系统通知标记为已读"""
    try:
        # 提取用户ID - 处理current_user可能是对象的情况
        user_id = current_user
        if hasattr(current_user, 'id'):
            user_id = current_user.id
        elif isinstance(current_user, dict) and 'id' in current_user:
            user_id = current_user['id']
        
        # 检查通知是否存在
        check_query = """
        SELECT id FROM system_notifications WHERE id = %s AND is_active = 1
        """
        notification = await database.fetch_one(check_query, (notification_id,))
        
        if not notification:
            raise HTTPException(status_code=404, detail="通知不存在或已被删除")
        
        # 插入或更新已读记录
        query = """
        INSERT INTO user_notification_reads (user_id, notification_id)
        VALUES (%s, %s)
        ON DUPLICATE KEY UPDATE read_at = CURRENT_TIMESTAMP
        """
        
        values = (user_id, notification_id)
        
        await database.execute(query, values)
        
        return {"message": "通知已标记为已读"}
    except HTTPException as e:
        raise e
    except Exception as e:
        logger.error(f"标记通知已读失败: {str(e)}")
        raise HTTPException(status_code=500, detail=f"标记通知已读失败: {str(e)}")

# 获取用户未读通知数量
@router.get("/user/unread-count")
async def get_unread_notification_count(current_user: int = Depends(get_current_user)):
    """获取用户未读通知数量"""
    try:
        # 提取用户ID - 处理current_user可能是对象的情况
        user_id = current_user
        if hasattr(current_user, 'id'):
            user_id = current_user.id
        elif isinstance(current_user, dict) and 'id' in current_user:
            user_id = current_user['id']
        
        query = """
        SELECT COUNT(*) as count
        FROM system_notifications n
        LEFT JOIN user_notification_reads r ON n.id = r.notification_id AND r.user_id = %s
        WHERE n.is_active = 1 AND r.id IS NULL
        """
        
        result = await database.fetch_one(query, (user_id,))
        
        return {"unread_count": result["count"] if result else 0}
    except Exception as e:
        logger.error(f"获取未读通知数量失败: {str(e)}")
        raise HTTPException(status_code=500, detail=f"获取未读通知数量失败: {str(e)}") 